package com.daxt.controller.filemanager;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.utils.DataBaseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.DataBackupsMapper;
import com.daxt.model.service.base.vo.DataBackups;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "数据还原")
@RestController
@RequestMapping("/dataBase")
public class DataBackupsController {

    @Autowired
    private DataBackupsMapper dataBackupsMapper;
    @Value(value = "${spring.datasource.username}")
    private String mysqlusername;
    @Value(value = "${spring.datasource.password}")
    private String mysqlpassword;
    @Value(value = "${spring.datasource.url}")
    private String mysqlUrl;


    private final Log log = LogFactory.getLog(DataBackupsController.class);


    @ApiOperation(value = "获取备份列表", notes = "")
    @GetMapping("/list")
    public Result<PageInfo<DataBackups>> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                              @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Page<DataBackups> page = new Page<>(pageNum == null ? 0 : pageNum,
                pageSize == null ? 10 : pageSize);
        QueryWrapper<DataBackups> queryWrapper = new QueryWrapper<DataBackups>();
        queryWrapper.orderByDesc("createTime");
        IPage<DataBackups> info = dataBackupsMapper.selectPage(page, queryWrapper);
        PageInfo<DataBackups> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
                info.getRecords());
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }

    @ApiOperation(value = "还原", notes = "")
    @GetMapping("/backups/{id}")
    public Result<String> backups(@PathVariable("id") String id) throws IOException, InterruptedException {
        DataBackups selectById = dataBackupsMapper.selectById(id);
        if (selectById == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "还原失败，备份信息不存在！！！", null);
        }

        try {
//            String str = mysqlDir + "mysql -u" + mysqlusername + " -p" + mysqlpassword + " -h " + ip + " daxt<" + mysqlBackupDir + selectById.getDataType() + File.separator + selectById.getFileName();
//            String cmds = " mysql -u" + mysqlusername + " -p" + mysqlpassword + " -h " + ip + " daxt<" + mysqlBackupDir + selectById.getDataType() + File.separator + selectById.getFileName();
            String type = selectById.getDataType();//手动备份
            String flag = "restore";//还原
            String fileName = selectById.getFileName();
            String dataBaseName=mysqlUrl.substring(mysqlUrl.indexOf("/",27)+1,mysqlUrl.indexOf("?"));
            if(DataBaseUtil.execMysql(fileName,mysqlusername,mysqlpassword,type,flag,"3306",dataBaseName)){
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "还原完成", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "还原失败！！！", null);




    }

    @ApiOperation(value = "备份", notes = "")
    @PostMapping("/backups/set")
    public Result<String> setBackups() {
        try {
            String type = "0";//手动备份
            String flag = "backup";//备份
            String fileName = IdWorker.getIdStr() + ".sql";
            String dataBaseName=mysqlUrl.substring(mysqlUrl.indexOf("/",27)+1,mysqlUrl.indexOf("?"));
            if(DataBaseUtil.execMysql(fileName,mysqlusername,mysqlpassword,type,flag,"3306",dataBaseName)){
                DataBackups entity = new DataBackups();
                entity.setCreateTime(LocalDateTime.now());
                entity.setDataType(type);
                entity.setFileName(fileName);
                dataBackupsMapper.insert(entity);
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "备份完成", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "备份失败！！！", null);

    }

    /*public static void main(String[] args) {

        System.out.println("2222222222:" );
    }*/


}
